//
//  NewTwoViewController.m
//  Item A House
//
//  Created by dlios on 15/5/25.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NewTwoViewController.h"
#import "RankTableViewCell.h"
#import "Reachability.h"
#import "RankModel.h"
#import "MainJumpViewController.h"
#import <UIImageView+WebCache.h>
#import "UIScrollView+PullLoad.h"
#import "SANetWorkingTask.h"
#import "SearchViewController.h"
#import "Singletion.h"
@interface NewTwoViewController ()<UITableViewDataSource, UITableViewDelegate, PullDelegate, UISearchBarDelegate>

@end

@implementation NewTwoViewController
- (void)dealloc
{
    [_search release];
    [_table release];
    [_array release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.count = 1;
        self.type = 1;
    }
    return self;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self createTable];
    [self getConnect];
    [self createSearch];
    
    
}
#pragma mark -
#pragma 判断是否有网封装
- (BOOL)stringFromStatus:(NetworkStatus)status
{
    BOOL a = YES;
    switch (status) {
        case NotReachable:
            a = NO;
            break;
        case ReachableViaWiFi:
        case ReachableViaWWAN:
            break;
        default:
            a = NO;
            break;
    }
    return a;
}
#pragma mark -
#pragma mark 网络请求
- (void)createNetwork
{

    Singletion *city = [Singletion shareManager];
    NSString *str = [NSString stringWithFormat:@"%ld", (long)self.count];
    NSDictionary *dic = @{@"city_id":city.cityid, @"page":str, @"page_size":@"10"};

    [SANetWorkingTask request:@"http://api.anjuke.com/xinfang/m/iphone/1.3/loupan/newlist/" parmater:dic block:^(NSDictionary *result) {
        NSMutableDictionary *myDic = [result objectForKey:@"result"];
        NSMutableArray *myArr = [myDic objectForKey:@"rows"];
        for (NSDictionary *my in myArr) {
            RankModel *model = [[RankModel alloc] init];
            [model setValuesForKeysWithDictionary:my];
            [self.array addObject:model];
            [model release];
        }
       
        
        
        [self.table reloadData];
        //根据计数type停止刷新或者下载
        if (self.type == 1) {
            [self.table stopLoadWithState:PullUpLoadState];
        }
        else {
            [self.table stopLoadWithState:PullDownLoadState];
        }
    }];
    
}
#pragma mark -
#pragma mark 上拉下载下拉刷新
// 用来判断是上拉加载还是下啦刷新, state为当前加载状态
- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    NSLog(@"%u",state);
    if (state == PullDownLoadState) {
        // 判断为下拉刷新, 2秒后执行downLoad方法
        [self getConnect];
    } else {
        
        // 判断为上拉加载, 2秒后执行方法
        [self loadMore];
    }
}
//上拉加载,计数器self.type来判断是下拉还是上拉,以便于上面的停止
- (void)loadMore
{
    self.count++;
    self.type = 1;
    [self createInformation];
}

// 下拉刷新
-(void)getConnect
{
    self.count = 1;
    self.type = 2;
    [self createInformation];
}
#pragma mark -
#pragma mark 判断有无网
- (void)createInformation
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if ([self stringFromStatus:status]) {
        [self createNetwork];
        NSLog(@"有网");
    } else {
        NSLog(@"无网");
        UIAlertView *ale = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请确认网络连接" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [ale show];
        [ale release];
    }
}
#pragma mark -
#pragma mark tableView
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.table.rowHeight = 100;
    [self.table registerClass:[RankTableViewCell class] forCellReuseIdentifier:@"ranktable"];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.pullDelegate = self;
    self.table.canPullDown = YES;
    self.table.canPullUp = YES;
    [self.view addSubview:self.table];
    [self.table release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
       return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RankTableViewCell *rank = [tableView dequeueReusableCellWithIdentifier:@"ranktable"];
    RankModel *model = [self.array objectAtIndex:indexPath.row];
    [rank.image sd_setImageWithURL:[NSURL URLWithString:model.default_image] placeholderImage:[UIImage imageNamed:@"10.jpg"]];;
    rank.loupan.text = model.loupan_name;
    rank.region.text = [NSString stringWithFormat:@"%@  %@", model.region_title, model.sub_region_title];
    rank.tags.text = model.tags;
    rank.price.text = [NSString stringWithFormat:@"%ld元/平", (long)model.price];
    return rank;
}
//跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        MainJumpViewController *jump = [[MainJumpViewController alloc] init];
        RankModel *model = [self.array objectAtIndex:indexPath.row];
        jump.loupan_id = model.loupan_id;
        jump.loupan_name = model.loupan_name;
        jump.rankModel = [self.array objectAtIndex:indexPath.row];
        jump.hidesBottomBarWhenPushed = YES;
    
    CATransition *trans = [CATransition animation];
    [self.navigationController pushViewController:jump animated:NO];
    trans.type = @"rippleEffect";
    trans.duration = 0.8f;
    [self.navigationController.view.layer addAnimation:trans forKey:nil];
        [jump release];
    
}
#pragma mark -
#pragma mark searchBar
- (void)createSearch
{
    self.search = [[UISearchBar alloc] initWithFrame:CGRectZero];
    [self.search setBackgroundColor:[UIColor brownColor]];
    [self.search setPlaceholder:@"搜索"];
    self.search.autocapitalizationType = UITextAutocorrectionTypeYes;
    self.search.showsCancelButton = NO;
    self.search.delegate = self;
    self.navigationItem.titleView = self.search;
    [self.search release];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.search resignFirstResponder];
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search autorelease];
}
- (void)viewDidAppear:(BOOL)animated
{
    [self createSearch];
}
@end
